import logging
from flask_restplus import Resource, Namespace, fields, marshal_with
from common.utils.decorators import login_required
from flask import g, request, jsonify, Response
from app.models import db
from app import redis_clent, app
from flask_restplus import reqparse, inputs
from app.tasks.test import test
from app.routes.car.schemas import CarSchemas
from .marshmallow import (
    CarDataSerializer,
    CarBodySerializer,
    CarListQuerySerializer,
    CarIdSerializer,
    CarCreateQuerySerializer,
    CarIdDeletedSerializer,
    CarIdPutdSerializer,
)
from ...models.car import CarInfo

LOG = logging.getLogger(__name__)

car_ns = Namespace("car")

car_schemas = CarSchemas(namespace=car_ns)


class CarListCreateView(Resource):
    # method_decorators = [login_required]

    @car_ns.doc(params=car_schemas.car_list_query())
    @car_ns.marshal_with(car_schemas.car_data())
    def get(self):
        cars, total = CarListQuerySerializer().load(data=request.args)
        response = CarDataSerializer().dump({"total": total, "data": cars})

        return response

    @car_ns.expect(car_schemas.car_create_query())
    @car_ns.marshal_with(car_schemas.car_id())
    def post(self):
        car_info = CarCreateQuerySerializer().load(data=request.json)

        response = CarIdSerializer().dump(car_info)
        return response


class CarPutDeleteView(Resource):
    # method_decorators = [login_required]

    @car_ns.expect(car_schemas.car_create_query())
    def put(self, id):
        request.json["id"] = id
        car_info = CarIdPutdSerializer().load(data=request.json)

        return Response(status=202 if car_info == 1 else 500)

    def delete(self, id):
        car_info = CarIdDeletedSerializer().load(data={"id": id})

        response = CarIdSerializer().dump(car_info)
        return Response(status=204 if response else 500)

    @car_ns.marshal_with(car_schemas.car_body())
    def get(self, id):
        # 查询记录详情
        try:
            car = CarInfo.query.get(id)
        except Exception as e:
            raise e

        response = CarBodySerializer().dump(car)

        return response
